package org.kitten.core.util;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 公共参数配置文件.会尝试读取user.dir下的config.properties<br>
 * 使用方法:<br>
 * 
 * <pre>
 * Sys as = Sys.getInstance();
 * String pageSize = as.get(&quot;page.size.defaultValue&quot;);
 * </pre>
 * 
 * 
 * @author cyper
 * @version 1.0
 */

public class Sys {
    private static final Log logger = LogFactory.getLog(Sys.class);
	private static Properties p = new Properties();
	private static Sys instance = new Sys();

	private Sys() {
		InputStream is = null;
		try {
			is = new FileInputStream(System.getProperty("user.dir")
					+ "/config.properties");
			p.load(is);
		} catch (Exception e) {
		    logger.error("在用户目录下没有发现【config.properties】属性文件");
		} finally {
			FileUtil.close(is);
		}
		logger.info("config.properties is reloaded.");
	}

	public static Sys getInstance() {
		if (instance == null) {
			instance = new Sys();
		}
		return instance;
	}

	public static void reload() {
		p.clear();
		instance = null;
		getInstance();
	}

	/**
	 * 根据传入的键值从accaud.properties中读取参数
	 * 
	 * @param key
	 * @return
	 */
	public String get(String key) {
		return p.getProperty(key);
	}

	public String get(String key, String defaultValue) {
		return p.getProperty(key, defaultValue);
	}

	public int getInt(String key) {
		return Integer.parseInt(p.getProperty(key));
	}

	public int getInt(String key, String defaultValue) {
		return Integer.parseInt(p.getProperty(key, defaultValue));
	}
	public Boolean getBoolean(String key) {
		return Boolean.valueOf(p.getProperty(key));
	}
	
	public Boolean getBoolean(String key,String defaultValue) {
		return Boolean.valueOf(p.getProperty(key,defaultValue));
	}

	public String getDir(String key) {
		String str = p.getProperty(key);
		if (str == null || str.endsWith("/") || str.endsWith("\\")) {
			return str;
		} else {
			return str + "/";
		}
	}

	public String getDir(String key, String defaultValue) {
		String str = p.getProperty(key, defaultValue);
		if (str == null || str.endsWith("/") || str.endsWith("\\")) {
			return str;
		} else {
			return str + "/";
		}
	}

	public static Properties getP() {
		return p;
	}

}
